/**
 * Created by zhangyida on 16/1/15.
 */
/* @flow */
'use strict';

import {
    StyleSheet,
    View,
    Navigator,
    Text,
    TouchableOpacity,
    TouchableHighlight,
    AlertIOS
} from 'react-native';
import React from 'react';
import URL from '../config/server';
import {Utils} from '../config/utils';
import tcomb from 'tcomb-form-native'
import Icon from 'react-native-vector-icons/Ionicons';
import DeviceInfo from 'react-native-device-info';

var Form = tcomb.form.Form;

var Pwd = tcomb.refinement(tcomb.String, function (value) {
    var Reg = /^(\w){6,18}$/;
    return Reg.test(value);
});

var User = tcomb.struct({
    qqCode: tcomb.String,
    password: Pwd,
    passwordRP: Pwd,
    inviteCode: tcomb.maybe(tcomb.String)
});

var NavigationBarRouteMapper = {
    LeftButton(route, navigator, index, navState) {
        return (
            <TouchableOpacity style={{flex: 1, justifyContent: 'center'}}
                              onPress={() => navigator.parentNavigator.pop()}>
                <View style={{flexDirection:'row',padding:5}}>
                    <Icon name="ios-arrow-back" size={18} color="#ffffff" style={{alignSelf:'center'}}/>
                    <Text style={{color: 'white', margin: 3,fontSize:16}}>
                        返回
                    </Text>
                </View>
            </TouchableOpacity>
        );
    },
    RightButton(route, navigator, index, navState) {
        return null;
    },
    Title(route, navigator, index, navState) {
        return (
            <Text style={{color: 'white', margin: 10, fontSize: 20}}>
                QQ注册
            </Text>
        );
    }
};

export default class RegMail extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            value: {
                qqCode: '',
                password: '',
                passwordRP: '',
                inviteCode: '',
                isSubmit: false
            },
            options: {
                auto: 'placeholders',
                fields: {
                    qqCode: {
                        placeholder: '请输入您QQ邮箱收到的验证码',
                        error: '验证码错误'
                    },
                    password: {
                        password: true,
                        placeholder: '请设置你的密码',
                        error: '密码长度在6~18之间，只能包含字符、数字和下划线'
                    },
                    passwordRP: {
                        password: true,
                        placeholder: '请再次输入您的密码',
                        error: '两次输入的密码不一致'
                    },
                    inviteCode: {
                        placeholder: '邀请码',
                        error: '无效的邀请码'
                    }
                }
            }
        };
    }

    checkCode(value) {
        var CHECK_MAIL_CODE = URL.checkCode + 'qq/' + this.props.message + '/' + value.qqCode;
        console.log(CHECK_MAIL_CODE);
        var that = this;
        Utils.get(CHECK_MAIL_CODE, function (data) {
            console.log(data);
            if (data) {
                console.log(that);
                console.log(value);
                that.setState({
                    options: tcomb.update(that.state.options, {
                        fields: {
                            qqCode: {
                                hasError: {'$set': false}
                            }
                        }
                    })

                });
                that.checkInvite(value);
            } else {
                console.log(that);
                that.setState({
                    options: tcomb.update(that.state.options, {
                        fields: {
                            qqCode: {
                                hasError: {'$set': true}
                            }
                        },
                    })
                });
            }
        });
    }

    checkInvite(value) {
        if (value.inviteCode == null) {
            this.sendMsg(value);
        } else {
            var CHECK_INVITE = URL.local + 'checkInviteCode?code=' + value.inviteCode;
            console.log(CHECK_INVITE);
            var that = this;
            Utils.get(CHECK_INVITE, function (data) {
                console.log(data);
                if (data) {
                    that.setState({
                        options: tcomb.update(that.state.options, {
                            fields: {
                                inviteCode: {
                                    hasError: {'$set': false}
                                }
                            }
                        })
                    });
                    that.sendMsg(value);
                } else {
                    that.setState({
                        options: tcomb.update(that.state.options, {
                            fields: {
                                inviteCode: {
                                    hasError: {'$set': true}
                                }
                            }
                        })
                    })
                }
            })
        }
    }

    sendMsg(value) {
        let that = this;
        this.setState({isSubmit: true})
        var REGISTER = URL.register + 'qq';
        var MSG = {
            qq: this.props.message,
            password: this.state.value.passwordRP,
            machineId: DeviceInfo.getUniqueID(),
            byzd1: this.state.value.inviteCode
        };
        var navigator = this.props.navigator;
        Utils.post(REGISTER, MSG, function (data) {
            if (data) {
                AlertIOS.alert(
                    '注册成功!'
                );
                navigator.push({
                    id: 'LoginPage',
                    message: {
                        title: '神秘涨停网',
                        regPhone: that.props.message
                    }
                })
            } else {
                AlertIOS.alert(
                    '注册失败!'
                );
                that.setState({isSubmit: false})
            }
        })
    }

    onPress() {
        var value = this.refs.main.refs.form.getValue();
        if (value) {
            if (value.password != value.passwordRP) {
                this.setState({
                    value: value,
                    options: tcomb.update(this.state.options, {
                        fields: {
                            passwordRP: {
                                hasError: {'$set': true}
                            }
                        }
                    })
                })
            } else {
                this.setState({
                    value: value,
                    options: tcomb.update(this.state.options, {
                        fields: {
                            passwordRP: {
                                hasError: {'$set': false}
                            }
                        }
                    })
                });
                this.checkCode(value);
            }
        }
    }

    renderScene(route, navigator) {
        return (
            <View style={styles.container}>
                <Form
                    ref='form'
                    type={User}
                    options={this.state.options}
                    value={this.state.value}
                    onChange={this.onChange}
                />
                <TouchableHighlight style={this.state.isSubmit?styles.forbButton:styles.button}
                                    onPress={this.state.isSubmit?()=>console.log('forbid'):this.onPress.bind(this)}
                                    underlayColor='#e02820'>
                    <Text style={styles.buttonText}>{this.state.isSubmit ? "正在注册.." : "立即注册"}</Text>
                </TouchableHighlight>

                <Text style={styles.h1}>
                    已向您的QQ邮箱发送了一封带有验证码的邮件,请您查收并填写验证码.
                </Text>
            </View>
        );
    }


    render() {
        return (
            <Navigator
                ref='main'
                renderScene={this.renderScene.bind(this)}
                navigator={this.props.navigator}
                navigationBar={
            <Navigator.NavigationBar
                style={{backgroundColor: '#e02820', alignItems: 'center'}}
                routeMapper={NavigationBarRouteMapper} />
          	}/>
        );
    }
}


const styles = StyleSheet.create({
    Index: {
        flex: 1
    },
    container: {
        marginTop: 100,
        justifyContent: 'center',
        padding: 20,
        backgroundColor: '#ffffff'
    },
    logo: {
        flex: 1,
        alignSelf: 'center',
        marginTop: 20
    },
    title: {
        fontSize: 25,
        alignSelf: 'center',
        marginBottom: 15,
        marginTop: 15
    },
    buttonText: {
        fontSize: 18,
        color: 'white',
        alignSelf: 'center'
    },
    button: {
        height: 36,
        backgroundColor: '#e02820',
        borderColor: '#e02820',
        borderWidth: 1,
        borderRadius: 8,
        marginBottom: 10,
        alignSelf: 'stretch',
        justifyContent: 'center'
    },
    findPwdText: {
        fontSize: 15,
        textDecorationLine: 'underline',
        textAlign: 'right'
    },
    h1: {
        fontSize: 15,
        marginLeft: 20,
        color: '#e02820'
    },
    forbButton: {
        height: 36,
        backgroundColor: '#333333',
        borderColor: '#333333',
        borderWidth: 1,
        borderRadius: 8,
        marginBottom: 10,
        alignSelf: 'stretch',
        justifyContent: 'center'
    }
});
